<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>观察者模式</title>
</head>

<body>
    <script>
        class Publisher {
            _state = 0;
            subscribers = []

            get state() {
                return this._state
            }
            set state(value) {
                this._state = value
                this.notify(value)
            }
            notify(value) {
                this.subscribers.forEach(subscriber => subscriber.update(value))
            }
            collect(subscriber) {
                this.subscribers.push(subscriber)
            }
        }
        let subId = 1
        class Subscriber {
            publisher = null;
            id = subId++;
            subscribe(publisher) {
                this.publisher = publisher
                publisher.collect(this)
            }
            update(value) {
                console.log(`我是${this.id}号订阅者，收到发布者信息：${value}`);
            }
        }
        let publisher = new Publisher()
        let subscriber1 = new Subscriber()
        let subscriber2 = new Subscriber()
        subscriber1.subscribe(publisher)
        subscriber2.subscribe(publisher)
        publisher.state = 2
        
    </script>
</body>

</html>